<?php

/**
 * 审批通过
 *
 * @param Object $apply_data
 *        	oa_application data from front end
 * @param $old_data
 *        	oa_application data from MySQL
 * @param string $comment
 *        	建议
 * @param $cur_emp_id
 *         当前员工ID
 * return true: or Error Array ['errcode':xxxxx,data:Object,'errmsg']
 */

function goto_next_step($apply_data,$old_data,$comment,$cur_emp_id,$appid,$formId=null,$is_app=true) {
    $map['id'] = $apply_data['flow_id'];
    $process = M('OaProcessFlow')->where($map)->find();

    $res = checkApprovalHop($apply_data,$old_data,$cur_emp_id);
    if($res['errcode'] !== 0){
        $return['errcode'] = $res['errcode'];
        $return['errmsg'] = $res['msg'];
        $return['data'] = null;
        return $return;
    }

    $operation = json_decode($process['operations']);
    if (false == checkNodeAccessRight($operation[$old_data['step']-1],$cur_emp_id,$is_app))
    {
        $return['errcode'] = '50002';
        $return['errmsg'] =error_msg($return,' 没有访问权限-checkNodeAccessRight');
        $return['data'] = $res;
        return $return;
    }
    $nodeName = M('OaNode')->where(array('id'=>$operation[$old_data['step']-1]))->getField('name');

    if (count($operation) < $apply_data['step']){
        $return['errcode'] = '61451';
        $return['errmsg'] = error_msg($return,'step 数据错误,超出流程步数');
        $return['data'] = null;
        return $return;
    }
    // var_dump($operation);
    $nodeOwners = getWhoHasTheRightAccessThisNode($operation[$apply_data['step']-1],$apply_data['dept_id']);

    if ( count($nodeOwners) == 1) {
        $apply_data['approver'] = $nodeOwners[0];
    } else if (count($nodeOwners) > 1){
        $apply_data['approver'] = 0;
    } else {
        $return['errcode'] = '61451';
        $return['errmsg'] = error_msg($return,'没有人有权限处理此节点');
        $return['data'] = null;
        return $return;
    }

    $apply_data['is_read'] = false;
    $apply_data['hops'] = $old_data['hops']+1;
    $apply_map['id'] = $apply_data['id'];
    if(M('OaApplication')->where($apply_map)->save($apply_data)){
        $log['appid'] = $appid;
        $log['emp_id'] = $apply_data['applyer'];
        $log['application_id'] = $apply_data['id'];
        $log['approver'] = $cur_emp_id;
        $log['step'] = $old_data['step'];
        $log['hop'] = $old_data['hops']+1;
        $log['status'] = 1;
        $log['result'] = true;
        $log['comment'] = $comment;
        $log['time'] = NOW_TIME;
        $log['node_name'] = $nodeName;
        $em_map['id'] = $log['approver'];
        $man = M('OaEmployee')->where($em_map)->find();
        $log['approver_name'] = $man['name'];
        M('OaProcessLog')->add($log);
        $emplist = $nodeOwners;
        foreach ( $emplist as $emp) {
            D('OaEmpMsg')->sendApprovingMsg($emp,$apply_data,true);
        }
        $apply_data['node_name'] = $nodeName;
        $apply_data['statusStr'] = '通过';
        $apply_data['approver'] = $cur_emp_id;
        $apply_data['approver_name'] = $man['name'];
        D('OaEmpMsg')->sendApprovalResultMsg($apply_data['applyer'],$apply_data,true);
    }

    return true;
}

/**
 *   申请单被驳回
 *
 * @param $old_data
 *        	oa_application data from MySQL
 * @param string $comment
 *        	建议
 *  * @param $cur_emp_id
 *         当前员工ID
 * return true: or Error Array ['errcode':xxxxx,data:Object,'errmsg']
 */
function approvalFail_goback ($comment,$old_data,$cur_emp_id,$appid,$formId=null,$is_app=true){
    $map['id'] = $old_data['flow_id'];
    $process = M('OaProcessFlow')->where($map)->find();
    $operation = json_decode($process['operations'],true);
    $node_id = $operation[$old_data['step']-1];
    if (false == checkNodeAccessRight($node_id,$cur_emp_id,$is_app))
    {
        $return['errcode'] = '50002';
        $return['errmsg'] = error_msg($return,' 没有访问权限');
        $return['data'] = $res;
        return $return;
    }
    $nd_map['id'] = $node_id;
    $node = M('OaNode')->where($nd_map)->find();
    if(empty($node['failback'])){
        $return['errcode'] = '61451';
        $return['errmsg'] =error_msg($return,' Node没有配置回退功能');
        $return['data'] = $res;
        return $return;
    }

    $old_step = $old_data['step'];
    $log_map['step'] = $node['failback'];
    $log_map['application_id'] = $old_data['id'];
    $log_map['appid'] = $appid;
    $logs = M('OaProcessLog')->where($log_map)->order('hop desc')->select();
    if(empty($logs)){
        $return['errcode'] = '61451';
        $return['errmsg'] =error_msg($return,' Log查找不到对应的记录');
        $return['data'] = $res;
        return $return;
    }
    $back_log = $logs[0];
    $old_data['step'] = $node['failback'];
    $old_data['approver'] = $back_log['approver'];
    $old_data['hops'] = $old_data['hops'] + 1;
    $old_data['is_read'] = true;
    $apply_map['id'] = $old_data['id'];
    if(M('OaApplication')->where($apply_map)->save($old_data)) {
        $log['appid'] = $appid;
        $log['emp_id'] = $old_data['applyer'];
        $log['application_id'] = $old_data['id'];
        $log['approver'] = $cur_emp_id;
        $log['step'] = $old_step;
        $log['hop'] = $old_data['hops'];
        $log['status'] = 1;
        $log['result'] = false;
        $log['comment'] = $comment;
        $log['time'] = NOW_TIME;
        $log['node_name'] = $node['name'];
        $em_map['id'] = $log['approver'];
        $man = M('OaEmployee')->where($em_map)->find();
        $log['approver_name'] = $man['name'];
        M('OaProcessLog')->add($log);
        $apply_data = $old_data;
        $apply_data['node_name'] = $nodeName;
        $apply_data['statusStr'] = '驳回';
        $apply_data['approver'] = $cur_emp_id;
        $apply_data['approver_name'] = $man['name'];
        return D('OaEmpMsg')->sendApprovalResultMsg($old_data['approver'],$apply_data,true);
    }

    return true;
}

/**
 * 处理申请单
 *
 * @param Object $apply_data
 *        	oa_application data from front end
 * @param int $cur_step
 *          当前级数
 * @param $go_next
 *        	0，保存，1：通过， 2：驳回
 * @param string $comment
 *        	建议
 *  * @param $cur_emp_id
 *         当前员工ID
 * return true: or Error Array ['errcode':xxxxx,data:Object,'errmsg']
 */
function process_reimburse_apply($apply_data,$cur_step,$go_next,$comment,$cur_emp_id,$appid,$formId=null,$is_app=true)
{
    if (empty($apply_data['id'])) {
        $return['errcode'] = '61451';
        $retrun['data'] = null;
        $return['errmsg'] = error_msg($return, 'apply_id 数据错误');
        return $return;
    }
    $apply_map['id'] = $apply_data['id'];
    $old_data = M('OaApplication')->where($apply_map)->find();

    if ($old_data['step'] != $cur_step) {
        $return['errcode'] = '61451';
        $return['data'] = null;
        $return['errmsg'] =error_msg($return, 'step 数据错误');
        return $return;
    }
    if ($go_next == 0) {
        if ($cur_step == 1) {
            $res = M('OaApplication')->where($apply_map)->save($apply_data);
        } else {
            $tmp_data['approver'] = $apply_data['approver'];
            $tmp_data['is_read'] = $apply_data['is_read'];
            $res = M('OaApplication')->where($apply_map)->save($tmp_data);
            if ($old_data['approver'] != $apply_data['approver']) {
                $res2 = D('OaEmpMsg')->sendmsg($appid,$formId,3, $apply_data['approver'], msg_reimbursementTook($apply_data));
                /*
                if ( $res2 !== true) {
                    $return['errcode'] = '61451';
                    $return['errmsg'] = error_msg($return, '发送消息失败');
                    $return['data'] = null;
                }
                */
            }
        }

        if ($res === false) {
            $return['errcode'] = '61451';
            $return['errmsg'] = error_msg($return, '保存数据失败');
            $return['data'] = null;
            return $return;
        }else{
            return true;
        }
    } else if ($go_next == 1) {
        return goto_next_step($apply_data, $old_data, $comment,$cur_emp_id,$appid,$formId,$is_app);
    } else if ($go_next == -1) {
        return approvalFail_goback($comment, $old_data,$cur_emp_id,$appid,$formId,$is_app);
    }else{
        $return['errcode'] = '61451';
        $return['data'] = null;
        $return['errmsg'] =error_msg($return, 'go_next` 数据错误');
        return $return;
    }

}

/**
 *   申请单完成
 *
 * @param int $apply_id
 *        	审批单ID
 * @param string $comment
 *        	建议
 * return true: or Error Array ['errcode':xxxxx,data:Object,'errmsg']
 */
function appliction_done($apply_id,$comment,$cur_emp_id,$appid,$formId=null,$is_app=true){
    $map['id'] = $apply_id;
    $old_data =  M('OaApplication')->where($map)->find();
    if(empty($old_data)){
        $return['errcode'] = '61451';
        $return['errmsg'] = error_msg($return,'apply_id 数据错误');
        $return['data'] = null;
        return $return;
    }
    $flow_map['id'] = $old_data['flow_id'];
    $process = M('OaProcessFlow')->where($flow_map)->find();
    $operation = json_decode($process['operations']);
    if (count($operation) != $old_data['step']){
        $return['errcode'] = '61451';
        $return['msg'] = error_msg($return,'step'.$old_data['step'].' 还没有到完成阶段'.count($operation));
        echo api_return($return['errcode'],null,$return['msg']);
    }
    if (false == checkNodeAccessRight($operation[$old_data['step']-1],$cur_emp_id,$is_app))
    {
        $return['errcode'] = '50002';
        $return['errmsg'] = error_msg($return,' 没有访问权限');
        $return['data'] = null;
        return $return;
    }
    $nodeName = M('OaNode')->where(array('id'=>$operation[$old_data['step']-1]))->getField('name');

    $old_data['status'] = true;
    $old_data['approve_date'] = NOW_TIME;
    $old_data['approver'] = 0;
    $old_data['is_read'] = false;
    $old_data['hops'] = $old_data['hops']+1;
    if(M('OaApplication')->where($map)->save($old_data)){
        $log['appid'] = $appid;
        $log['emp_id'] = $old_data['applyer'];
        $log['application_id'] = $old_data['id'];
        $log['approver'] = $cur_emp_id;
        $log['step'] = $old_data['step'];
        $log['hop'] = $old_data['hops'];
        $log['status'] = 1;
        $log['result'] = true;
        $log['comment'] = $comment;
        $log['time'] = NOW_TIME;
        $log['node_name'] = $nodeName;
        $em_map['id'] = $log['approver'];
        $man = M('OaEmployee')->where($em_map)->find();
        $log['approver_name'] = $man['name'];
        M('OaProcessLog')->add($log);
        D('OaEmpMsg')->sendmsg($appid,$formId,3,$old_data['applyer'],msg_reimbursementDone($old_data));
    }
    return true;
}

/**
 *   创建一个申请单
 *
 * @param object $data
 *        	{type:xxxx,emp_id:xxx,..}
 * @param object $type
 *         application_type From MySql
 *  * @param object $dept
 *         $dept From MySqlx
 * @param int &$apply_id
 *         a pointer value to return the new ID in oa_application.
 * return true: or Error Array ['errcode':xxxxx,data:Object,'errmsg']
 */
function create_one_application($data,$type,$dept,$approver,$appid,&$apply_id){

    if(empty($type) || empty($dept)){
        $return['errcode'] = '9001001';
        $return['errmsg'] = error_msg( $return) ;
        $return['data'] = null;
        return $return;
    }else{
        $data['step'] = 1;
        $data['appid'] = $appid;
        $data['is_read'] = false;
        $data['status'] = false;
        // $data['is_del'] = false;
        $data['approver'] = $approver;
        $apply = M('OaApplication')->add($data);
        if ($apply < 1) {
            $return['errcode'] = '50001';
            $return['errmsg'] =error_msg( $return,"申请单创建失败") ;
            $return['data'] = null;
            return $return;
        }else{
            $data['apply_no'] = generateApplyNo($type['sn'], $apply);
            $data['submit_date'] = NOW_TIME;
            $apply_map['id'] = $apply;
            M('OaApplication')->where($apply_map)->save($data);
            $apply_id = $apply;
        }
    }
    return true;
}

function getMyApprovalBufferPool ($cur_emp_id,$type=null) {
    if (empty($type)) {
        $flows = M('OaProcessFlow')->select();
    }else {
        $flows = M('OaProcessFlow')->where(array('type'=>$type))->select();
    }
    // var_dump('getMyApprovalBufferPool empid:'.$cur_emp_id);
    $accessNodes = getEmpAllaccessNode($cur_emp_id);
    // var_dump($accessNodes);
    $applications = Array();
    foreach ($flows as $flow) {
        $operations = json_decode($flow['operations']);
        $map['flow_id'] = intval($flow['id']);
        $map['status'] = 0;
        $map['is_del'] = 0;
        $map['is_read'] = 0;
        $map['approver'] = 0;
        for( $i = 0,$step=1; $i< count($operations);$i++,$step++){
            if(in_array($operations[$i],$accessNodes)){
                unset($map['dept_id']);
                $map['step'] = $step;
                $node = M('OaNode')->where(array('id'=>$operations[$i]))->find();
                if($node['scope'] == 'S'){
                    $nodeRoles = M('OaRoleNode')->where(array('node_id'=>$node['id']))->select();
                    $roleIdStr = '';
                    foreach ($nodeRoles as $nodeRole) {
                        $roleIdStr = $roleIdStr.$nodeRole['role_id'].',';
                    }
                    // var_dump('roleIdStr'.$roleIdStr);
                    $roleIdStr = substr($roleIdStr,0,strlen($roleIdStr)-1);
                    $emp_rl_map['emp_id'] = $cur_emp_id;
                    $emp_rl_map['role_id'] = array('in',$roleIdStr);
                    $empRoles = D('OaUserRoleView')->where($emp_rl_map)->select();
                    // var_dump($empRoles);
                    $deptIds = array();
                    foreach ($empRoles as $empRole){
                        if (empty($empRole['role_deptid'])){
                            $empDept = D('OaEmployeeDeptView')->where(array('id'=>$cur_emp_id))->find();
                            $tmpDeptIds = findallDeptsInTargetGrade($empDept,$node['dept_grade']);
                            $deptIds = array_merge($deptIds,$tmpDeptIds);
                        } else {
                            // var_dump('empRole->role_deptid:'.$empRole['role_deptid']);
                            findallDeptsInThisDept($empRole['role_deptid'],$deptIds);
                        }
                    }
                    $listStr = implode(",", $deptIds);
                    // var_dump('deptIds'.$listStr);
                    $map['dept_id'] = array('in',$listStr);
                }
                if(!empty($type)){
                    $map['type'] = $type;
                }
                // var_dump($map);
                $tmps = D('OaApplicationView')->where($map)->select();
                $applications = array_merge ($applications,$tmps);
                // var_dump($applications);
            }
        }
    }

    array_multisort(array_column($applications, 'submit_date'), SORT_DESC, $applications);
    return $applications;
}

function getAttendanceBufferPool ($cur_emp_id) {
    $flow_map['type'] = array('in',array(1,2));
    $flows = M('OaProcessFlow')->where($flow_map)->select();
    $empRoles = M('OaUserRole')->where(array('emp_id'=>$cur_emp_id))->select();
    $empRolesId = array_column($empRoles,'role_id');
    $applications = array();
    foreach ($flows as $flow) {
        $operations = json_decode($flow['operations']);
        $map['flow_id'] = intval($flow['id']);
        $map['status'] = 0;
        $map['is_del'] = 0;
        // $map['is_read'] = 0;
        $map['approver'] = 0;
        for( $i = 0,$step=1; $i< count($operations);$i++,$step++){
            if(in_array($operations[$i],$empRolesId)){
                $map['step'] = $step;
                $map['type'] = array('in',array(1,2));
                $tmps = D('OaApplicationView')->where($map)->select();
                $applications = array_merge ($applications,$tmps);
            }
        }
    }
    // var_dump($applications);
    return $applications;
}